package com.huiquan.framework.utils;

import java.util.List;

import javax.mail.Message;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Component;

/**
 * @ClassName: EMailUtil
 * @Description: 发送邮件工具类
 * @version V1.0
 */
@Component
public class EMailUtil {

    @Value("${email.sendFrom}")
    private String emailEendFrom;
    
	private JavaMailSender javaMailSender;
	private String preSubject = "【标注系统】";

	public void setJavaMailSender(JavaMailSender javaMailSender) {
		this.javaMailSender = javaMailSender;
	}

	// 发送单个html模板邮件
	/**
	 * @Title：sendMessage
	 * @Description: 
	 * @version V1.0
	 * @param content：邮件内容
	 * @param subject：邮件标题
	 * @param address:收件人邮箱地址
	 * @throws Exception
	 *             void
	 */
	public void sendMessage(String content, String subject, String address) throws Exception {
		MimeMessage msg = javaMailSender.createMimeMessage();
		// 设置utf-8或GBK编码，否则邮件会有乱码，true表示为multipart邮件
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
		helper.setTo(address); // 邮件接收地址
		helper.setFrom(emailEendFrom); // 邮件发送地址,这里必须和xml里的邮件地址相同一致
		helper.setSubject(subject); // 主题
		helper.setText(content, true); // 邮件内容，注意加参数true，表示启用html格式
		javaMailSender.send(msg); // 发送邮件
	}

	/**
	 * @Title：sendBatchEmail
	 * @Description: 群发邮件
	 * @version V1.0
	 * @param content：邮件内容
	 * @param subject：邮件标题
	 * @param address：收件人地址列表
	 * @throws Exception
	 *             void
	 */
	@SuppressWarnings("static-access")
	public void sendBatchEmail(String content, String subject, List<String> address) throws Exception {
		MimeMessage msg = javaMailSender.createMimeMessage();
		MimeMessageHelper helper = new MimeMessageHelper(msg, true, "utf-8");
		String toList = getMailList(address);
		InternetAddress[] iaToList = new InternetAddress().parse(toList);
		msg.setRecipients(Message.RecipientType.TO, iaToList);
		// 设置邮件名
		helper.setFrom(emailEendFrom);
		helper.setSubject(preSubject + subject);
		helper.setText(content, true); // 邮件内容，注意加参数true，表示启用html格式
		javaMailSender.send(msg);
	}

	// 列表地址转化为字符串分割的地址String
	private String getMailList(List<String> to) {
		StringBuffer toList = new StringBuffer();
		int length = to.size();
		if (to != null && length != 0) {
			if (length < 2) {
				toList.append(to.get(0));
			} else {
				for (int i = 0; i < length; i++) {
					toList.append(to.get(i));
					if (i != (length - 1)) {
						toList.append(",");
					}
				}
			}
		}
		return toList.toString();
	}

}
